require 'yaml'

class Album

  attr_accessor :artist, :title, :lyrics

  def initialize(map=nil)
    @lyrics=[]
    map.each do |k,v|
      send("#{k}=",v)
    end if map
  end
  
  def to_s
    "Album: #{artist} : #{title} (#{lyrics.size} songs)"
  end

  def <=>(other)
    @title<=>other.title
  end
  
  def << lyrics
    lyrics.each do |l|
      l.tracknum=99 if l.tracknum.nil?
      @lyrics << l
    end
    @lyrics.sort!{|a,b| a.tracknum<=>b.tracknum}
  end
  
  def save
    s1=[]
    @lyrics.each do |l|
      s1 << {:tracknum=>l.tracknum, :artist=>l.artist, :title=>l.title }
    end
    obj={:title=>@title, :artist=>@artist, :lyrics=>s1}
    rs=YAML::dump(obj)
  end
  
  def self.load obj
    data=YAML::load(obj)
    album=Album.new({:artist=>data[:artist], :title=>data[:title]})
    data[:lyrics].each do |l|
      album << [Lyric.new({:artist=>l[:artist], :title=>l[:title],:tracknum=>l[:tracknum]})]
    end unless data[:lyrics].nil?
    album
  end
  
end
